import 'package:cbec_app/components/base/base_ctr.dart';
import 'package:cbec_app/components/http/network.dart';
import 'package:cbec_app/routes/routes.dart';
import 'package:cbec_app/utils/AppData.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:decimal/decimal.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:flutter/services.dart';
import '../../../components/app_conifg.dart';
import '../../../components/popup/prepayment_card_popup.dart';
import '../../../components/popup/score_discount_popup.dart';
import '../../../utils/EventMgr.dart';

///
class PendingPaymentController extends BaseController {
  Map data = {};

  Map extra = {};

  Map prepareFinalPayMap = {};

  // 物流信息
  List transportInfo = [];

  bool isIconTitle = false;

  bool hasRecommend = false;

  bool hasTransInfo = false;

  List goodsInfo = [];

  String title = "";

  // 订单类型 0-普通代发订单 1-自建商品订单 2-特价订单 3-秒杀订单 4-拼团订单 5-预售订单 6-卡券订单 7-充值订单 8-砍价订单
  int type = 0;

  int status = 0;

  double tabHeight = 0;

  double paddingTop = 0;

  Map? orderInfo;

  Map? expressInfo;

  // 是否需要 预售支付尾款
  bool needPayFinal = false;
  //----------------红包-----------------//
  ///可用红包列表
  List redPackList = [];

  ///已选红包id
  List useRedPackIds = [];

  ///红包用于显示的金额
  String showRedPackPrice = '暂无可用';

  ///红包优惠金额
  double useRedPackPrice = 0;

  //----------------积分-----------------//
  String showPointsPrice = '暂无可用';

  // 选择的积分
  double haveUsePoints = 0;

  ///积分抵扣金额
  double pointsDiscountAmount = 0;

  ///积分配置信息
  Map<String, dynamic> pointsInfo = {};

  //----------------预付卡-----------------//
  String showCardPrice = '暂无可用';

  ///预付卡抵扣金额
  double cardDiscountAmount = 0;

  ///预付卡配置信息
  Map<String, dynamic> payCardInfo = {};

  ///实际支付价格
  double actualPrice = 0.0;

  /// 定金预售，待支付尾款
  double finalPay = 0.0;

  /// 是否已经锁单，
  int isOrder = 1;

  /// 是否有保税商品
  bool hasBonded = false;

  @override
  void onInit() {
    final String id = Get.arguments;
    getOrderDetail(id);
    super.onInit();
  }

  ///复制单号
  void copy(String text) async {
    await Clipboard.setData(ClipboardData(text: text));
    Tools.showToast("订单号已复制");
  }

  ///再来一单
  void argin(List goodsInfo, int type) {
    //print('goodsInfo ===== $goodsInfo');
    Tools.showModal(
        content: "确定要再来一单么?",
        onCancel: (tag) => {},
        onConfirm: (tag) {
          Map<String, dynamic> params = {};
          params['type'] = type;
          params['client'] = GetPlatform.isIOS ? AppConfig.clientIos : AppConfig.clientAndroid;
          params['goodsList'] = getPlaceOrderGoodsList(goodsInfo);
          params['sid'] = AppData.sid;
          params['addressId'] = '';
          SmartDialog.dismiss(tag: tag);
          //print('确定要再来一单 ==== $params');
          Get.toNamed(Routes.fillOrder, arguments: params);
        });
  }

  ///下单商品列表
  List<Map<String, dynamic>> getPlaceOrderGoodsList(List goodsInfo) {
    List<Map<String, dynamic>> arr = [];
    for (var goods in goodsInfo) {
      Map<String, dynamic> info = {};
      info['buyNum'] = goods['buyNum'];
      info['goodsId'] = goods['goodsId'];
      info['isSelect'] = 1;
      info['isSend'] = goods['isSend'];
      info['specNum'] = goods['specNum'];
      arr.add(info);
    }
    return arr;
  }

  ///确认收货
  receive(String orderId) {
    Tools.showModal(
      content: "是否确认收货?",
      onCancel: (tag) => {},
      onConfirm: (tag) {
        Tools.showLoading();
        Network.receive(orderId).then((value) {
          if (value) {
            EventMgr.send(EventType.refreshOrderList);
            EventMgr.send(EventType.refreshLogin);
            SmartDialog.dismiss(tag: tag);
            Tools.showToast("收货成功");
            getOrderDetail(orderId);
            update();
          }
          Tools.hideLoading();
        }).catchError((error) {
          Tools.hideLoading();
        });
      },
    );
  }

  //获取详情
  void getOrderDetail(String id) {
    Tools.showLoading();
    Network.getOrderDetail(id).then((value) {
      Tools.hideLoading();
      print('获取详情 $value');
      try {
        orderInfo = value;
        if (value['expressInfo'] != null) {
          expressInfo = value['expressInfo'];
          transportInfo = value['expressInfo']?['additionalProperties1'] ?? [];
        }
        type = value['type'];
        goodsInfo = value['goodsInfo'];
        hasBonded = value['goodsInfo'].any((item) => item['commodityType'] == 1);
        data = value;
        extra = value['extra'];
        String finalPayString = value['finalPay'] != null ? value['finalPay'].toString() : '0.0';
        finalPay = double.parse(finalPayString); // 转换为 double，如果为 null 则使用默认值
        refreshPayFinalPrice();
        bool isPreSale = value['type'] == 5;
        int presaleType = value['presaleType'];
        int finalStatus = value['finalStatus'];
        bool boolValue = isPreSale && presaleType == 2 && finalStatus == 0;
        if (isPreSale) {
          // 预售状态 0-还没有到付尾款时间 1-正在进行尾款 2-尾款付款时间已结束
          int presaleStatus = value['presaleStatus'];
          bool isPayFinal = presaleStatus == 1;
          needPayFinal = boolValue && isPayFinal;
          print('needPayFinal ======= $needPayFinal');
        }
        titleStatus();
        if (needPayFinal) {
          prepareFinalPay();
          getCanUsedPoints();
          getCanUsePayCard();
        }
        update();
      } catch (e) {
        // print('什么牛马 ==== $e');
      }
    }).catchError((error) {
      Tools.hideLoading();
      //print(error);
    });
  }

  void titleStatus() {
    // 0-已取消 10-待支付 20-待发货 30-已发货 40-已签收 50-已完成
    status = orderInfo?['status'];
    switch (status) {
      //待付款
      case 10:
        title = "等待付款";
        isIconTitle = true;
        tabHeight = 20;
        paddingTop = 15;
        break;
      //待发货
      case 20:
        title = needPayFinal ? "待付尾款" : "正在出库";
        isIconTitle = true;
        hasRecommend = true;
        hasTransInfo = false;
        break;
      //已发货
      case 30:
        title = "待收货";
        isIconTitle = true;
        hasTransInfo = true;
        break;
      //已签收
      case 40:
        title = "待评价";
        isIconTitle = true;
        hasTransInfo = true;
        break;
      //已完成
      case 50:
        title = "已完成";
        hasTransInfo = true;
        break;
      //已取消
      case 0:
        title = "已取消";
        isIconTitle = true;
        break;

      default:
    }
  }

  ///取消订单
  void cancelOrder() {
    Tools.showLoading();
    final String id = Get.arguments;
    Network.cancelOrder(id).then((value) {
      if (value) {
        Tools.showToast("已取消");
        Get.back();
      }
      Tools.hideLoading();
    }).catchError((error) {
      Tools.hideLoading();
    });
  }

  /// deleteOrder
  void deleteOrder() {
    Tools.showLoading();
    final String id = Get.arguments;
    Network.deleteOrder(id).then((value) {
      if (value) {
        Tools.showToast("已删除");
        Get.back();
      }
      Tools.hideLoading();
    }).catchError((error) {
      Tools.hideLoading();
    });
  }

  // 支付尾款
  void payBalance() {
    if (Tools.isPresaleEnded(orderInfo?['presaleEndTime'])) {
      Tools.showToast('支付尾款时间结束');
      return;
    }
    var paySn = orderInfo?['paySn'];
    var finalPay = orderInfo?['finalPay'];
    var orderTime = orderInfo?['cd'];
    Get.toNamed(
      '${Routes.cashier}/?sn=$paySn&price=$finalPay&cd=$orderTime',
      arguments: {'hasBonded': hasBonded},
    );
  }

  /// 获取可用红包
  void prepareFinalPay() {
    Tools.showLoading();
    final String id = Get.arguments;
    Map<String, dynamic> param = {'orderId': id};
    Network.getPrepareFinalPay(param).then((value) {
      Tools.hideLoading();
      prepareFinalPayMap = value;
      isOrder = value['isOrder']; // 预售单的时候，是否点了支付锁单
      redPackList = value['redDnvelopeList'];
      redPackList.isNotEmpty ? showRedPackPrice = '请选择' : showRedPackPrice = '暂无可用';
    }).catchError((error) {
      Tools.hideLoading();
    });
  }

  ///获取可用积分
  Future getCanUsedPoints() {
    Tools.showLoading();
    Map<String, dynamic> params = {};
    pointsDiscountAmount = 0;
    cardDiscountAmount = 0;
    showCardPrice = '请选择';
    refreshPayFinalPrice();

    params['goodsList'] = getPointsCardParams();
    //预售订单
    if (orderInfo?['presaleType'] != null) {
      params['money'] = orderInfo?['priceOrder'];
    }
    params['type'] = 2;
    return Network.getCanUsePoints(params).then((value) {
      Tools.hideLoading();
      pointsInfo = value;
      // print('获取可用积分 ==== $value');
      value['maxUsePoints'] > 0 ? showPointsPrice = '请选择' : showPointsPrice = '暂无可用';
      update();
    }).catchError((onError) {
      Tools.hideLoading();
    });
  }

  // 获取可用预付卡
  Future getCanUsePayCard() {
    Tools.showLoading();
    cardDiscountAmount = 0;
    Map<String, dynamic> params = {};
    params['goodsList'] = getPointsCardParams(haveCard: true);
    //预售订单
    if (orderInfo?['presaleType'] != null) {
      params['money'] = orderInfo?['priceOrder'];
    }
    params['type'] = 2;
    if (pointsInfo['pointsRadio'] == null) {
      Decimal pointsDiscountAmountDecimal = Decimal.parse(pointsDiscountAmount.toStringAsFixed(2));
      params['points'] = pointsDiscountAmountDecimal;
    } else {
      int pointsRadio = pointsInfo['pointsRadio'];
      Decimal pointsDiscountAmountDecimal = Decimal.parse(pointsDiscountAmount.toStringAsFixed(2));
      Decimal pointsRadioDecimal = Decimal.fromInt(pointsRadio);
      Decimal result = pointsDiscountAmountDecimal * pointsRadioDecimal;
      params['points'] = result;
    }
    return Network.getCanUsePayCard(params).then((value) {
      Tools.hideLoading();
      // print('预付卡 $value');
      payCardInfo = value;
      value['maxUseBdPayCardBalance'] > 0 ? showCardPrice = '请选择' : showCardPrice = '暂无可用';
      update();
    }).catchError((onError) {
      Tools.hideLoading();
    });
  }

  double calculatePrice() {
    double price = finalPay - useRedPackPrice - pointsDiscountAmount;
    return price;
  }

  double calculatePrice2() {
    double price = finalPay - useRedPackPrice - cardDiscountAmount;
    return price;
  }

  List<Map<String, dynamic>> getPointsCardParams({bool haveCard = false}) {
    List<Map<String, dynamic>> arr = [];
    Map<String, dynamic> info = {};
    for (var item in goodsInfo) {
      info['buyNum'] = item['buyNum'];
      info['commodityType'] = item['commodityType'];
      info['goodsId'] = item['goodsId'];
      info['price'] = item['price'];
      info['priceActual'] = item['priceActual'];
      info['priceExpress'] = item['priceExpress'];
      info['pricePay'] = haveCard ? calculatePrice2() : calculatePrice();
      info['priceTax'] = item['priceTax'];
      info['priceTotal'] = item['priceTotal'];
      info['totalNum'] = item['totalNum'];
      arr.add(info);
    }
    return arr;
  }

  ///确定使用红包
  void useRedPack(String id, String price) {
    useRedPackIds = id.split(',');
    showRedPackPrice = double.parse(price) > 0 ? '-￥$price' : '-￥0';
    useRedPackPrice = double.parse(price);
    // TODO 刷新金额
    pointsDiscountAmount = 0.0;
    haveUsePoints = 0.0;
    cardDiscountAmount = 0.0;

    getCanUsedPoints();
    getCanUsePayCard();

    refreshPayFinalPrice();

    update();
  }

  ///选择积分支付
  void selectPointsPay() async {
    await getCanUsedPoints();
    showScoreDiscountPopup(
      info: pointsInfo,
      onConfirm: (discountAmount) {
        usePointsDiscount(discountAmount);
      },
    );
  }

  ///确定使用积分抵扣
  void usePointsDiscount(String discountAmount) {
    showPointsPrice = double.parse(discountAmount) > 0 ? '-￥$discountAmount' : '请选择';
    pointsDiscountAmount = double.parse(discountAmount);
    haveUsePoints = double.parse(discountAmount) * pointsInfo['pointsRadio'];
    // 根据优先级 重置 预付卡
    cardDiscountAmount = 0.0;
    showCardPrice = '请选择';
    // 刷新金额
    refreshPayFinalPrice();
    update();
  }

  ///选择预付卡支付
  void selectCardPay() async {
    await getCanUsePayCard();
    showPrepaymentCardPopup(
      info: payCardInfo,
      onConfirm: (discountAmount) {
        useCardDiscount(discountAmount);
      },
    );
  }

  ///确定使用预付卡抵扣
  void useCardDiscount(String discountAmount) {
    showCardPrice = double.parse(discountAmount) > 0 ? '-￥$discountAmount' : '请选择';
    cardDiscountAmount = double.parse(discountAmount);
    // 刷新金额
    refreshPayFinalPrice();
    update();
  }

  // 刷新支付尾款的金额
  void refreshPayFinalPrice() {
    double temp = finalPay - useRedPackPrice - pointsDiscountAmount - cardDiscountAmount;
    String tempString = (finalPay - useRedPackPrice - pointsDiscountAmount - cardDiscountAmount).toStringAsFixed(2);
    actualPrice = temp >= 0 ? double.parse(tempString) : 0;

    update();
  }

  /// 定金预售付尾款提交
  void payPlaceOrderFinalPay() {
    Map<String, dynamic> params = {};
    var points = haveUsePoints;
    final String id = Get.arguments;
    params['orderId'] = id;
    params['payWayCode'] = '';
    params['points'] = points;
    params['pointsMoney'] = pointsDiscountAmount;
    params['preMoney'] = cardDiscountAmount;
    params['redPacketId'] = useRedPackIds;
    params['sid'] = AppData.sid;

    Tools.showLoading();
    Network.getPlaceOrderFinalPay(params).then((value) {
      Tools.hideLoading();

      // 这里刷一下页面状态
      final String id = Get.arguments;
      getOrderDetail(id);
      Future.delayed(const Duration(seconds: 1), () {
        if (Tools.isPresaleEnded(orderInfo?['presaleEndTime'])) {
          Tools.showToast('支付尾款时间结束');
          return;
        }
        var paySn = value['paySn'];
        var finalPay = value['priceOrder'];
        var orderTime = orderInfo?['cd'];

        if (finalPay > 0) {
          Get.toNamed(
            '${Routes.cashier}/?sn=$paySn&price=$finalPay&cd=$orderTime',
            arguments: {'hasBonded': hasBonded},
          );
        } else {
          Get.toNamed('${Routes.paySuccess}/?price=$finalPay&paySelected=0');
        }
      }).catchError((error) {
        // print('error ==== $error');
        Tools.hideLoading();
      });
    });
  }
}
